import zlib

class Park:
    def __init__(self):
        self.app_identify = b"watch app 0x00000001".ljust(32)
        self.bootloader_identify = b"watch bootloader 0x00000001".ljust(32)

    def print_identify(self):
        print("static const uint8_t app_identify[32]={",end="")
        i = 0
        for b in self.app_identify:
            print("0x%02x"%b,end="")
            if i< 32-1:
                print(",",end="")
            i = i+1            
        print("};")

        print("static const uint8_t bootloader_identify[32]={",end="")
        i = 0
        for b in self.bootloader_identify:
            print("0x%02x"%b,end="")
            if i< 32-1:
                print(",",end="")
            i = i+1            
        print("};")
        
    def app(self,file,out_file):
        with open(file,"rb") as f:
            data = f.read(1024*1024)

            if data[0:32] == self.app_identify:
                print("app already parked");
                return
            
            crc = zlib.crc32(data);
            size = len(data)

            new_file = out_file

            with open(new_file,"wb") as f_new:
                f_new.write(self.app_identify)
                f_new.write(crc.to_bytes(4))
                f_new.write(size.to_bytes(4))
                f_new.write(data)
                
            print(new_file, "%d + 40"%(len(data)))

    def bootloader(self,file,out_file):
        with  open(file,"rb") as f:
            data = f.read(1024*1024)

            if data[0:32] == self.bootloader_identify:
                print("bootloader alread parked")
                return
            crc = zlib.crc32(data)
            size = len(data)
            new_file = out_file 

            with open(new_file,"wb") as f_new:
                f_new.write(self.bootloader_identify)
                f_new.write(crc.to_bytes(4))
                f_new.write(size.to_bytes(4))
                f_new.write(data)
            
            print(new_file, "%d +40"%(len(data)))


park = Park()
park.print_identify()
park.app(r"E:\dataset\watch\software\app\Debug\watch_main.bin",r"C:\Users\nwz\Desktop\temp\one\app_park.bin")
park.bootloader(r"E:\dataset\watch\software\bootloader\Debug\watch_bootloader.bin",r"C:\Users\nwz\Desktop\temp\one\boot_loader_park.bin")